// The Effect of Promoting Savings on Informal Risk-Sharing:
// Experimental Evidence from Vulnerable Women in Kenya
// Felipe Dizon, Erick Gong, and Kelly Jones


// DATASETS 
// figures: isave_mpesause, isave_corecollapse2, isave_extdcollapse2 
// tables: risave_3p, risave_3pb, risave_shocks, risave_isave_extdlong_dyad_all, risave_isave_extdlong_dyad_all_dir, risave_isave_corelong

clear all
clear matrix
clear mata
set more off

cd "/Users/felipedizon/Dropbox/Research/isave/iSAVE/Outputs/Papers/savings_irsa/submission-JHR/publication/Replication Package" 

gl DATA "DATA"
gl OUTPUT "OUTPUT"

********************************************************************************
// FIGURES
********************************************************************************

// FIGURE 1
// study design
********************************************************************************

	// not in stata

// FIGURE 2
// study timeline
********************************************************************************

	// not in stata

// FIGURE 3
// support partners
********************************************************************************

	use ${DATA}/risave_collapse3.dta, clear 	
	
	#delimit ;
	
	twoway (hist e_count_0_bm, discrete color(gs10)) 
	(hist e_count_0_bout, discrete fcolor(none) lcolor(black)), 
	legend(order(1 "In-sample risk-sharing" 2 "In-sample charitable-out" ) size(small)) 
	note("Notes: Each bin indicates the proportion of the sample with that number of reported financial support partners." 
	"A risk-sharing partner is a mutual support partner, defined as a person where the respondent reports yes to"
	"both questions: (1) could you rely on this person for help if she needed money urgently to pay for an expense?"
	"and (2) could this person rely on you for help if she needed money urgently to pay for an expense? A charitable"
	"-out partner is an individual who could rely on the respondent for support, but who the respondent could not"
	"rely on for support; i.e. the respondent reported yes to question (2), but not to question (1).", size(small)) 
	xtitle("Number of Baseline Partners") graphregion(color(white)) xlabel(#10);
	
	 #delimit cr
	
	graph export ${OUTPUT}/figure3.png, as(png) replace		

// FIGURE 4
// transfers between partners
********************************************************************************

	#delimit ;
	
	graph bar (mean) in_max2 out_max2 inonly2 outonly2, bargap(3) 
	bar(1, fcolor(gs5)) bar(2, color(gs10)) 
	bar(3, fcolor(none) lwidth(medthin) lpattern(solid) lcolor(black)) bar(4, fcolor(none) lwidth(medthin) lpattern(dash) lcolor(black))  
	ytitle("Mean Potential Transfers (Ksh)") graphregion(color(white)) blabel(bar, pos(inside) size(vsmall)) 
	legend(label(1 "receive from risk-sharing partner") label(2 "send to risk-sharing partner") label(3 "receive from charity-in partner") label(4 "send to charity-out partner") size(small)) 
	note("Notes: For each financial support partner, we ask: what is the maximum amount that this person (you) would"
	"give you (this person) in the event that you (this person) faced an unexpected expense? The responses generate"
	"a measure of potential transfers. The value presented above is the mean of the potential transfers across a"
	"respondent's set of baseline in-sample risk-sharing (charitable) partners, and across all respondents.", size(small)); 
	
	#delimit cr
	
	graph export ${OUTPUT}/figure4.png, as(png) replace
	
// FIGURE 5
// labeled account usage
********************************************************************************

	use ${DATA}/risave_mpesause.dta, clear

	 #delimit ;
	
	twoway (line acc2_bal_use date, sort)
	(line acc2_dep_use date, sort lpattern(longdash)),
	xline(19879, lcolor(edkblue)) 
	ylabel(#5, grid axis(1)) ytitle(Balance/Deposits in Ksh) 
	xtitle(Date) xlabel(#6, angle(45)) 
	legend(label(1 "Mean Balance for Adopters") label(2 "Mean Deposits for Adopters") size(vsmall) cols(3)) 
	note("", size(small)) 
	graphregion(color(white));
	 #delimit cr
	
	graph export ${OUTPUT}/figure5_a.png, as(png) replace
	
	 #delimit ;
	
	twoway (line acc2_use date, sort lcolor(black) yaxis(1) )
	(line acc2_cdep_use date, sort lpattern(longdash) lcolor(green) yaxis(2) ),
	xline(19879, lcolor(edkblue)) 
	ylabel(#5, grid axis(1)) ytitle(Cumulative Adoption Rate, axis(1)) ytitle(Cumulative Deposits in Ksh, axis(2)) 
	xtitle(Date) xlabel(#6, angle(45)) 
	legend(label(1 "Cumulative Adoption") label(2 "Mean Cumulative Deposits, Adopters") size(small) cols(2)) 
	note("", size(small)) 
	graphregion(color(white));
	#delimit cr
	
	graph export ${OUTPUT}/figure5_b.png, as(png) replace
	
	/*
	Notes: Using administrative safaricom records, we calculate the daily cumulative proportion of the treated"
	"sample that had used the new labeled account at least once since the beginning of treatment for all treated"
	"respondents. We define these individuals as adopters. We then create an individual by day dataset, where the"
	"balance for each day is the end of day balance for each individual. Then, for each day, we calculate the mean"
	"balance across all adopters, and the mean deposits across all adopters. The vertical solid line indicates the" 
	"end of the intense intervention period.
	*/
	
// FIGURE 6
// identification strategy
********************************************************************************

	// not in stata
*/

********************************************************************************
// TABLES
********************************************************************************

// TABLE 1
// Descriptives and balance
********************************************************************************

	gl Ha "table1-descriptive"
	gl Hb "table1-balance"
	
	use "${DATA}/risave_3p.dta", clear
	
	egen b_nf_expense30 =rowtotal(b_solarpanel b_battery b_events b_funeral b_medicine ///
	b_healthexp b_familyplan b_homeimp b_hhassets b_electronics)
	
	// subsample mean
	bys b_subsample: eststo: estpost summarize ///
	b_hhsize b_marstat3 b_marstat4 b_educ_sec ///
	b_income_pastweek b_temptationexpense b_nf_expense30 b_livestockval b_assetval_nonlstock b_hf_scale4 ///
	b_hypsave b_roscaany b_rosca_maxreceipt b_save_totalbal /// 
	b_is_have1 b_is_balance1 b_is_have2 b_is_balance2 b_is_have3 b_is_balance3 b_is_have4 b_is_balance4 b_loansany  ///
	b_tr_othperson0 b_tr_number b_transfersin b_in_forshock b_tro_othperson0 b_tro_number b_transfersout b_tro_forshock 
	
	// full sample mean
	estpost summarize ///
	b_hhsize b_marstat3 b_marstat4 b_educ_sec ///
	b_income_pastweek b_temptationexpense b_nf_expense30 b_livestockval b_assetval_nonlstock b_hf_scale4 ///
	b_hypsave b_roscaany b_rosca_maxreceipt b_save_totalbal /// 
	b_is_have1 b_is_balance1 b_is_have2 b_is_balance2 b_is_have3 b_is_balance3 b_is_have4 b_is_balance4 b_loansany  ///
	b_tr_othperson0 b_tr_number b_transfersin b_in_forshock b_tro_othperson0 b_tro_number b_transfersout b_tro_forshock 
	eststo esttotal
	
	// full sample balance
	estpost ttest ///
	b_hhsize b_marstat3 b_marstat4 b_educ_sec ///
	b_income_pastweek b_temptationexpense b_nf_expense30 b_livestockval b_assetval_nonlstock b_hf_scale4 ///
	b_hypsave b_roscaany b_rosca_maxreceipt b_save_totalbal /// 
	b_is_have1 b_is_balance1 b_is_have2 b_is_balance2 b_is_have3 b_is_balance3 b_is_have4 b_is_balance4 b_loansany  ///
	b_tr_othperson0 b_tr_number b_transfersin b_in_forshock b_tro_othperson0 b_tro_number b_transfersout b_tro_forshock ///
	,by(i_treat) 
	eststo tcfull
	
	// follow-up sample balance (i.e. non-attritors)
	gen attrited=cond(e2_enumerator==.,1,0)
	estpost ttest ///
	b_hhsize b_marstat3 b_marstat4 b_educ_sec ///
	b_income_pastweek b_temptationexpense b_nf_expense30 b_livestockval b_assetval_nonlstock b_hf_scale4 ///
	b_hypsave b_roscaany b_rosca_maxreceipt b_save_totalbal /// 
	b_is_have1 b_is_balance1 b_is_have2 b_is_balance2 b_is_have3 b_is_balance3 b_is_have4 b_is_balance4 b_loansany  ///
	b_tr_othperson0 b_tr_number b_transfersin b_in_forshock b_tro_othperson0 b_tro_number b_transfersout b_tro_forshock ///
	if attrited==0,by(i_treat) 
	eststo tcfollowup
	
	#delimit ;
	
	esttab esttotal est1 est2 using "${OUTPUT}/${Ha}", replace csv 
	cells("mean(fmt(a2))") label nodepvar nostar unstack 
	varlabel(b_hhsize "Household size" b_marstat3 "Widowed" b_marstat4 "Divorced or separated" b_educ_sec "Has more than primary education"
	b_income_pastweek "Income in past 7 days" 
	b_temptationexpense "Spending on temptation goods in past 7 days" b_nf_expense30 "Spending on non-food expenses in past 30 days"
	b_livestockval "Resale value of livestock assets" b_assetval_nonlstock "Value of non-livestock assets" b_hf_scale4 "Severely food insecure (HFIA scale)"
	b_hypsave "Max emergency can cover by self-financing" b_roscaany "Member in at least one ROSCA" b_rosca_maxreceipt "Last amount received from ROSCA (highest"
	b_save_totalbal "Total savings balance in all accounts" b_is_have1 "Has MPESA" b_is_balance1 "MPESA: current balance"
	b_is_have2 "Has other mobile banking" b_is_balance2 "Other mobile: current balance" b_is_have3 "Has formal bank account"
	b_is_balance3 "Formal account: current balance" b_is_have4 "Has other informal savings" b_is_balance4 "Informal savings: current balance"
	b_loansany "Any loan in past 12 months" b_tr_othperson0 "Can rely on at least 1 person for support" b_tr_number "Number of people can rely on"
	b_transfersin "Total amount received in past 3 months" b_in_forshock "Total amount received that is for shocks" 
	b_tro_othperson0 "Sent money to at least one person in past 3 months" b_tro_number "Number of people sent money to" 
	b_transfersout "Total amount sent in past 3 months" "Total amount sent that is for shocks") 
	addnotes("Notes: Temptation goods include jewelry, perfume, cosmetics, clothing, hairdressing, snacks, airtime, meals outside the home,
 cigarettes, alcohol and recreational drugs. Other non-food expenses include car battery, wedding and social events, funeral, health,
 expenses, family planning, electronics, household assets and home improvement. The following purposes are considered transfers for shocks:
 medical, wedding, funeral, or food consumption expenses. Values are reported in Kenyan Shillings (Ksh), 85 Ksh = 1 USD at the time of the study."); 	
	
	#delimit cr
	
	#delimit ;
	
	esttab tcfull tcfollowup using "${OUTPUT}/${Hb}", replace csv
	b(a2) label not nodepvar star(* 0.1 ** 0.05 *** 0.001) unstack 
	varlabel(b_hhsize "Household size" b_marstat3 "Widowed" b_marstat4 "Divorced or separated" b_educ_sec "Has more than primary education"
	b_income_pastweek "Income in past 7 days" 
	b_temptationexpense "Spending on temptation goods in past 7 days" b_nf_expense30 "Spending on non-food expenses in past 30 days"
	b_livestockval "Resale value of livestock assets" b_assetval_nonlstock "Value of non-livestock assets" b_hf_scale4 "Severely food insecure (HFIA scale)"
	b_hypsave "Max emergency can cover by self-financing" b_roscaany "Member in at least one ROSCA" b_rosca_maxreceipt "Last amount received from ROSCA (highest"
	b_save_totalbal "Total savings balance in all accounts" b_is_have1 "Has MPESA" b_is_balance1 "MPESA: current balance"
	b_is_have2 "Has other mobile banking" b_is_balance2 "Other mobile: current balance" b_is_have3 "Has formal bank account"
	b_is_balance3 "Formal account: current balance" b_is_have4 "Has other informal savings" b_is_balance4 "Informal savings: current balance"
	b_loansany "Any loan in past 12 months" b_tr_othperson0 "Can rely on at least 1 person for support" b_tr_number "Number of people can rely on"
	b_transfersin "Total amount received in past 3 months" b_in_forshock "Total amount received that is for shocks" 
	b_tro_othperson0 "Sent money to at least one person in past 3 months" b_tro_number "Number of people sent money to" 
	b_transfersout "Total amount sent in past 3 months" "Total amount sent that is for shocks") 
	addnotes("Notes: Temptation goods include jewelry, perfume, cosmetics, clothing, hairdressing, snacks, airtime, meals outside the home,
 cigarettes, alcohol and recreational drugs. Other non-food expenses include car battery, wedding and social events, funeral, health,
 expenses, family planning, electronics, household assets and home improvement. The following purposes are considered transfers for shocks:
 medical, wedding, funeral, or food consumption expenses. Values are reported in Kenyan Shillings (Ksh), 85 Ksh = 1 USD at the time of the study."); 	
	
	#delimit cr
	
	estimates clear
	
// TABLE 2
// Shocks and coping
********************************************************************************

	gl Ha "table2-shocks"
	gl Hb "table2-coping"
	
	// percent of women facing shocks
	
	use "${DATA}/risave_3p.dta", clear
	
	foreach x in illnessown illness birth death joblossown jobloss foodprice sellprice /// 
	theft damage legal conflict croploss sicklivestock deadlivestock {
	egen `x'=anymatch(e1_rc_`x' e2_rc_`x'), values(1)
	replace `x'=. if e1_surveydate==. & e2_surveydate==. 
	}
	
	bys b_subsample: eststo: estpost summarize ///
	illnessown illness birth death joblossown jobloss /// 
	theft sicklivestock deadlivestock 
	
	#delimit ;
	
	esttab est1 est2 using "${OUTPUT}/${Ha}", replace csv
	cells("mean(fmt(2))") label nodepvar nostar unstack 
	varlabel(illnessown "Own illness or injury" illness "Illness or injury in household" birth "Birth" death "Death"
	joblossown "Own job loss" jobloss "Job loss of main income earner" 
	theft "Theft" sicklivestock "Major illness of livestock" deadlivestock "Death of livestock") 
	addnotes(""); 	
	
	#delimit cr
	
	estimates clear
	
	// risk-coping strategies triggered by shocks
	
	use "${DATA}/risave_shocks.dta", clear
	
	// excluded shocks
	drop if shock==25 | shock==26 | shock==27 | shock==29 | shock==30 
	drop if shock==37 | shock==41 | shock==45 | shock==46 | shock==47 | shock==49
	
	foreach i of numlist 1/9 {
	egen cope`i'=anymatch(e_rc_riskcope e_rc_riskcope_oth1 e_rc_riskcope_oth2 e_rc_riskcope_oth3), values(`i')
	replace cope`i'=. if cope`i'!=1
	replace cope`i'=0 if e_rc_challenge==1 & cope`i'!=1
	}
	egen cope10=anymatch(e_rc_riskcope), values(10)
	replace cope10=. if cope10!=1
	replace cope10=0 if e_rc_challenge==1 & cope10!=1
	
	gen subsample="Kisumu" if rid<20000
	replace subsample="Kadibo" if rid>20000
	
	bys subsample: eststo: estpost summarize cope1 cope2 cope3 cope4 cope5 cope6 cope7 cope8 cope9 cope10 
	
	#delimit ;
	
	esttab est1 est2 using "${OUTPUT}/${Hb}", replace csv
	cells("mean(fmt(2))") label nodepvar nostar unstack 
	varlabel(cope1 "Borrowed money" cope2 "Sought assistance" cope3 "Tried to increase earnings"
	cope4 "Sold something" cope5 "Reduced expenses" cope6 "Relied on own savings" cope7 "Assistance in exchange for sex"
	cope8 "Engaged in spiritual efforts" cope9 "Other" cope10 "Nothing") 
	addnotes(""); 	
	
	#delimit cr
	
	estimates clear
	

// TABLE 3 
// impacts on savings
********************************************************************************

	// See separate DO file 

// TABLE 4
// impacts on risk-sharing (dyadic)
********************************************************************************

	set more off
	gl Ha "table4-basedyads"
	gl Hb "table4-alldyads"
	
	use "${DATA}/risave_extdlong_dyad_all.dta", clear
	
	// outcomes
	gl outcomes "max_in_2 max_out_2 amount_in_2 amount_out_2"
	gl outcomest "amount_in_2 amount_out_2"
		
	foreach x in max_in_2 max_out_2 amount_in_2 amount_out_2 {
	egen `x'=rowmax(`x'_i `x'_j)
	}	
	replace max_in_2=0 if mutual_2_i==0 & mutual_2_j==0
	replace max_out_2=0 if mutual_2_i==0 & mutual_2_j==0
		
	// estimation- baseline risk-sharing
	gl sample "(mutual_0_i==1 | mutual_0_j==1) & platnet_merge!=2" 
	
	foreach Y in $outcomes {
	regdyad2 `Y' treat_ij_b treat_ij_a i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'a
	}
	
	foreach Y in $outcomest {
	tobit `Y' treat_ij_b treat_ij_a i.pclusterid age_ij_a age_ij_b if ${sample}, ll vce(cl pclusterid)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'at
	}
	
	// estimation- overall risk-sharing
	gl sample "platnet_merge!=2"
	foreach Y in $outcomes {
	regdyad2 `Y' treat_ij_b treat_ij_a i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'b
	}
	
	foreach Y in $outcomest {
	tobit `Y' treat_ij_b treat_ij_a i.pclusterid age_ij_a age_ij_b if ${sample}, ll vce(cl pclusterid)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'bt
	}
	
	#delimit ;
	
	esttab max_in_2a max_out_2a amount_in_2a amount_out_2a amount_in_2at amount_out_2at using "${OUTPUT}/${Ha}", replace csv							
	b(1) se(1) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid age* _cons)      
	wrap varwidth(70) varlabel(treat_ij_a "($\hat{\beta_{2}}$) \textit{i} or \textit{j} treatment" treat_ij_b "($\hat{\beta_{1}}$) \textit{i} and \textit{j} treatment") 
	modelwidth(10) mlabels ("Insurance In" "Insurance Out" "Amount In" "Amount Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes: Unit of observation is an undirectional dyad \textit{ij}> where dependent variable is a measure of risk-sharing at endline. 
	We take the maximum of the report of \textit{i} and \textit{j} as the dyad-level observation.
	Sample in panel A includes all dyads which were risk-sharing at baseline. 
	Sample in panel B includes all possible dyads within each geographic cluster. 
	Estimation procedure used in columns 1 to 4 is OLS with dyadic-robust standard errors.
	Estimation procedure used in columns 5 to 6 is Tobit> with standard errors clustered at the geographic cluster level.
	Standard errors are shown in parentheses. Level of significance: *** p<0.01> ** p<0.05> * p<0.10.
	Values are reported in Kenyan Shillings (Ksh)> 85 Ksh = 1 USD at the time of the study.
	Included as regressors but not shown: absolute age difference between \textit{i} and \textit{j}> sum of age of \textit{i} and \textit{j}> geographic cluster fixed effects> and a constant.");	

	esttab max_in_2b max_out_2b amount_in_2b amount_out_2b amount_in_2bt amount_out_2bt using "${OUTPUT}/${Hb}", replace csv 							
	b(1) se(1) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid age* _cons)      
	wrap varwidth(60) varlabel(treat_ij_a "($\hat{\beta_{2}}$) \textit{i} or \textit{j} treatment" treat_ij_b "($\hat{\beta_{1}}$) \textit{i} and \textit{j} treatment") 
	modelwidth(10) mlabels ("Insurance In" "Insurance Out" "Amount In" "Amount Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes:"); 	
	
    #delimit cr
	
// TABLE 5
// impacts on risk-sharing (i-level)
********************************************************************************

	set more off
	gl Ha "table5-sum"
	gl Hb "table5-maximum"
	
	use "${DATA}/risave_3pb.dta", clear
	
	// outcomes
	gl outcomes1 "e2_net_rsnmutual e2_net_maxin_m e2_net_maxout_m e2_net_transinamt_m e2_net_transoutamt_m"
	gl outcomes2 "e2_net_rsnmutual_b e2_net_maxin_m_mx e2_net_maxout_m_mx e2_net_transinamt_m_mx e2_net_transoutamt_m_mx"

	// estimation
	foreach Y in $outcomes1 {
	reg `Y' i_treat i.pclusterid b_age, vce(robust)
	qui sum `Y' if i_treat==0 
	estadd scalar Ymean = r(mean)
	eststo `Y'
	}
	
	foreach Y in $outcomes2 {
	reg `Y' i_treat i.pclusterid b_age, vce(robust)
	qui sum `Y' if i_treat==0 
	estadd scalar Ymean = r(mean)
	eststo `Y'
	}
	
	// output latex tables
	
	#delimit ;
	
	esttab $outcomes1 using "${OUTPUT}/${Ha}", replace csv 							
	b(1) se(1) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid *age _cons)      
	wrap varwidth(50) varlabel(i_treat "($\hat{\beta_{1}}$) \textit{i} is treatment") 
	modelwidth(10) mlabels ("At least 1 Partner" "Insurance In" "Insurance Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes: Unit of observation is an individual \textit{i}> where dependent variable is a measure of risk-sharing at endline. 
	Outcome variables in panel A is total value of a risk-sharing measure across all endline risk-sharing partners. 
	Outcome variables in panel B is maximum value of risk-sharing measure across all endline risk-sharing partners. 
	Estimation procedure used is OLS with robust standard errors.
	Standard errors are shown in parentheses. Level of significance: *** p<0.01> ** p<0.05> * p<0.10.
	Values are reported in Kenyan Shillings (Ksh), 85 Ksh = 1 USD at the time of the study.
	Included as regressors but not shown: age> geographic cluster fixed effects> and a constant.");
	
	esttab $outcomes2 using "${OUTPUT}/${Hb}", replace csv 							
	b(1) se(1) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid *age _cons)      
	wrap varwidth(50) varlabel(i_treat "($\hat{\beta_{1}}$) \textit{i} is treatment") 
	modelwidth(10) mlabels ("At least 1 Partner" "Insurance In" "Insurance Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes:"); 	
	
    #delimit cr
	
// TABLE 6 
// state contingent transfers
********************************************************************************

	set more off
	gl H "table6"
	
	use "${DATA}/risave_extdlong_dyad_all_dir.dta", clear
		
	// treatment
	gen treat_ij_c=(treat_i-treat_j)
	gen treat_ij_d=(treat_i+treat_j)
	
	gen treat_ix=cond(treat_i==1 & treat_j!=1, 1, 0)
	gen treat_jx=cond(treat_j==1 & treat_i!=1, 1, 0)
	
	gen control_ij=cond(treat_i!=1 & treat_j!=1, 1, 0)
	
	// shocks and interactions
	foreach x in shockx_any_2_i shockx_any_2_j {
	gen x`x'=cond(`x'==1,0,cond(`x'!=.,1,.))
	gen ti_`x'=treat_i*`x'
	gen ti_x`x'=treat_i*x`x'
	gen tj_`x'=treat_j*`x'
	gen tj_x`x'=treat_j*x`x'
	gen tij_`x'=treat_ij_b*`x'
	gen tij_x`x'=treat_ij_b*x`x'
	gen tix_`x'=treat_ix*`x'
	gen tix_x`x'=treat_ix*x`x'
	gen tjx_`x'=treat_jx*`x'
	gen tjx_x`x'=treat_jx*x`x'
	gen cij_`x'=control_ij*`x'
	gen cij_x`x'=control_ij*x`x'
	}
	
	// estimation- baseline risk-sharing 
	gl sample "(mutual_0_i==1) & platnet_merge!=2" 
	
	regdyad2 amount_in_2_i tij_shockx_any_2_i tix_shockx_any_2_i tjx_shockx_any_2_i ///
	tij_xshockx_any_2_i tix_xshockx_any_2_i tjx_xshockx_any_2_i shockx_any_2_i i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum amount_in_2_i if treat_i==0 & treat_j==0 & shockx_any_2_i==1 & ${sample}
	estadd scalar Ymean = r(mean)
	test tij_shockx_any_2_i=tij_xshockx_any_2_i
	estadd scalar chisq1 = r(p)
	test tix_shockx_any_2_i=tix_xshockx_any_2_i
	estadd scalar chisq2 = r(p)
	test tjx_shockx_any_2_i=tjx_xshockx_any_2_i
	estadd scalar chisq3 = r(p)
	eststo sc1
	
	// estimation- overall risk-sharing
	gl sample "platnet_merge!=2"
	
	regdyad2 amount_in_2_i tij_shockx_any_2_i tix_shockx_any_2_i tjx_shockx_any_2_i ///
	tij_xshockx_any_2_i tix_xshockx_any_2_i tjx_xshockx_any_2_i shockx_any_2_i i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum amount_in_2_i if treat_i==0 & treat_j==0 & shockx_any_2_i==1 & ${sample}
	estadd scalar Ymean = r(mean)
	test tij_shockx_any_2_i=tij_xshockx_any_2_i
	estadd scalar chisq1 = r(p)
	test tix_shockx_any_2_i=tix_xshockx_any_2_i
	estadd scalar chisq2 = r(p)
	test tjx_shockx_any_2_i=tjx_xshockx_any_2_i
	estadd scalar chisq3 = r(p)
	eststo sc2
	
	// output latex tables
	
	#delimit ;
	
	esttab sc1 sc2 using "${OUTPUT}/${H}", replace csv						
	b(2) se(2) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean chisq1 chisq2 chisq3) drop(*pclusterid age* _cons)      
	wrap varwidth(90) varlabel()
	modelwidth(10) mlabels ("Amount In" "Amount In") 
	nonotes addnotes("Notes: Unit of observation is a directional dyad \textit{ij}> where dependent variable is actual transfers in the 4-month period before endline. 
	Sample in column 1 includes dyads which were risk-sharing at baseline. 
	Sample in column 2 includes all possible dyads within each geographic cluster. 
	Estimation procedure used is OLS with dyadic-robust standard errors.
	Standard errors are shown in parentheses. Level of significance: *** p<0.01> ** p<0.05> * p<0.10.
	Values are reported in Kenyan Shillings (Ksh)> 85 Ksh = 1 USD at the time of the study.
	Included as regressors but not shown: absolute age difference between \textit{i} and \textit{j}> sum of age of \textit{i} and \textit{j}> geographic cluster fixed effects> and a constant.");
	
    #delimit cr

// TABLE 7
// charitable support pairs
********************************************************************************

	set more off
	gl Ha "table7-baseinsample"
	gl Hb "table7-allinsample"
	gl Hc "table7-unrestricted"
	
	// in-sample pairs
	
	use "${DATA}/risave_extdlong_dyad_all_dir.dta", clear
	
	// outcomes
		gl outcomesa "max_in_2_i amount_in_2_i"
		gl outcomesb "max_out_2_i amount_out_2_i"
		
	// treatment
	gen treat_ix=cond(treat_i==1 & treat_j!=1, 1, 0)
	gen treat_jx=cond(treat_j==1 & treat_i!=1, 1, 0)
	
	// estimation (baseline)
	// never risk-sharing, one-way IN relations
	gl sample "(mutual_0_i!=1) & (mutual_2_i!=1) & (givecash_0_i==1) & platnet_merge!=2" 
	
	foreach Y in $outcomesa {
	regdyad2 `Y' treat_ij_b treat_ix treat_jx i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'1
	}
	
	// never risk-sharing, one-way OUT relations
	gl sample "(mutual_0_i!=1) & (mutual_2_i!=1) & (needcash_0_i==1) & platnet_merge!=2" 
	
	foreach Y in $outcomesb {
	regdyad2 `Y' treat_ij_b treat_ix treat_jx i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'1
	}
	
	// estimation (overall)
	// not endline risk-sharing, one-way IN relations
	gl sample "(mutual_2_i!=1) & platnet_merge!=2" 
	
	foreach Y in $outcomesa {
	regdyad2 `Y' treat_ij_b treat_ix treat_jx i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'2
	}
	
	// not endline risk-sharing, one-way OUT relations
	gl sample "(mutual_2_i!=1) & platnet_merge!=2" 
	
	foreach Y in $outcomesb {
	regdyad2 `Y' treat_ij_b treat_ix treat_jx i.pclusterid age_ij_a age_ij_b if ${sample}, dyads(rid_all netid_all)
	qui sum `Y' if treat_ij_a==0 & treat_ij_b==0 & ${sample}
	estadd scalar Ymean = r(mean)
	eststo `Y'2
	}
	
	// output latex tables
	
	#delimit ;
	
	esttab max_in_2_i1 max_out_2_i1 amount_in_2_i1 amount_out_2_i1 using "${OUTPUT}/${Ha}", replace csv 							
	b(2) se(2) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid age* _cons)      
	wrap varwidth(95) varlabel()
	modelwidth(10) mlabels ("Insurance In" "Insurance Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes: Unit of observation is a directional dyad \textit{ij}> where dependent variable is a measure of support at endline. 
	All samples in panels A to C exclude dyads which were risk-sharing at endline. 
	Sample in panel A and B uses only in-sample dyads> while sample in panel C uses only unrestricted dyads.
	For panel A and C> sample in columns 1 and 3 includes dyads which were charitable-in at baseline. 
	For panel A and C> sample in columns 2 and 4 includes dyads which were charitable-out at baseline. 
	For panels A and B> estimation procedure used is OLS with dyadic-robust standard errors.
	For panel C> Estimation procedure is OLS with clustered standard errors at the \textit{i}-level.
	Standard errors are shown in parentheses. Level of significance: *** p<0.01> ** p<0.05> * p<0.10.
	Values are reported in Kenyan Shillings (Ksh)> 85 Ksh = 1 USD at the time of the study.
	Included as regressors but not shown: absolute age difference between \textit{i} and \textit{j}> sum of age of \textit{i} and \textit{j}> geographic cluster fixed effects> and a constant.");
	
	esttab max_in_2_i2 max_out_2_i2 amount_in_2_i2 amount_out_2_i2 using "${OUTPUT}/${Hb}", replace csv 							
	b(2) se(2) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid age* _cons)      
	wrap varwidth(95) varlabel()
	modelwidth(10) mlabels ("Insurance In" "Insurance Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes:"); 	
	
    #delimit cr	
		
	// unrestricted pairs (baseline only)
	
	use "${DATA}/risave_corelong.dta", clear
	xtset rid
	
	// sample: only includes never risk-sharing, limited to baseline one-way IN relations 
	gl samplea "listtype_2!=. & (mutual_bma_2!=1) & (mutual_in_2!=1 & mutual_out_2!=1) & ((bp_in_2==1 | bd_in_2==1 | bi_in_2==1) & bp_out_2!=1 & bd_out_2!=1 & bi_out_2!=1)"  
	
	// sample: only includes never risk-sharing, limited to baseline one-way OUT relations 
	gl sampleb "listtype_2!=. & (mutual_bma_2!=1) & (mutual_in_2!=1 & mutual_out_2!=1) & (bp_in_2!=1 & bd_in_2!=1 & bi_in_2!=1 & (bp_out_2==1 | bd_out_2==1 | bi_out_2==1))"  
	
	// outcomes
	replace max_in_2=xmax_in_2 if xmax_in_2!=. & (max_in_2==0 | max_in_2==.)
	replace max_out_2=xmax_out_2 if xmax_out_2!=. & (max_out_2==0 | max_out_2==.)
	winsor2 max_in_2 max_out_2 amount_in_2 amount_out_2, replace cuts(0 99)
	gl outcomesa "max_in_2 amount_in_2"
	gl outcomesb "max_out_2 amount_out_2" 
	
	// estimation
	
	foreach Y in $outcomesa {
	reg `Y' i_treat i.clusterid b_age if ${samplea}, vce(cl rid)
	qui sum `Y' if i_treat==0 & ${samplea}
	estadd scalar Ymean = r(mean)
	eststo `Y'
	}
	foreach Y in $outcomesb {
	reg `Y' i_treat i.clusterid b_age if ${sampleb}, vce(cl rid)
	qui sum `Y' if i_treat==0 & ${sampleb}
	estadd scalar Ymean = r(mean)
	eststo `Y'
	}
	
	#delimit ;
	
	esttab max_in_2 max_out_2 amount_in_2 amount_out_2 using "${OUTPUT}/${Hc}", replace csv							
	b(1) se(1) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean, labels("Observations" "Mean in Control")) drop(*clusterid b_age _cons)  
	wrap varwidth(40) varlabel(i_treat "($\hat{\beta_{1}}$) \textit{i} treatment") 
	modelwidth(10) mlabels ("Insurance In" "Insurance Out" "Amount In" "Amount Out") 
	nonotes addnotes("Notes:");	
 
	#delimit cr


// TABLE 8
// impacts on welfare
********************************************************************************

	set more off
	gl H "table8"
	
	use "${DATA}/risave_extdlong_dyad_all_dir.dta", clear
	
	// treatment
	gen treat_ij_c=(treat_i-treat_j)
	gen treat_ij_d=(treat_i+treat_j)
	
	gen treat_ix=cond(treat_i==1 & treat_j!=1, 1, 0)
	gen treat_jx=cond(treat_j==1 & treat_i!=1, 1, 0)
	
	gen control_ij=cond(treat_i!=1 & treat_j!=1, 1, 0)
	
	// outcomes	
		replace f_enoughspend_a_0_i=0 if f_enoughspend_a_0_i==.
		replace f_enoughspend_a_2_i=0 if f_enoughspend_a_2_i==. & f_enoughspend_2_i!=.
		
		// reverse measures		
		foreach x in hf_score_0_i hf_score_0_j hf_score_2_i hf_score_2_j {
		gen r`x'=-`x'
		}
		
		gen rf_enoughspend_a_0_i=-f_enoughspend_a_0_i
		gen rf_enoughspend_a_2_i=-f_enoughspend_a_2_i
		
	gl outcomes "rhf_score rf_enoughspend_a laddnow" 
	
	// shocks and interactions
	foreach x in shockx_any_2_i shockx_any_2_j {
	gen x`x'=cond(`x'==1,0,cond(`x'!=.,1,.))
	gen ti_`x'=treat_i*`x'
	gen ti_x`x'=treat_i*x`x'
	gen tj_`x'=treat_j*`x'
	gen tj_x`x'=treat_j*x`x'
	gen tij_`x'=treat_ij_b*`x'
	gen tij_x`x'=treat_ij_b*x`x'
	gen tix_`x'=treat_ix*`x'
	gen tix_x`x'=treat_ix*x`x'
	gen tjx_`x'=treat_jx*`x'
	gen tjx_x`x'=treat_jx*x`x'
	gen cij_`x'=control_ij*`x'
	gen cij_x`x'=control_ij*x`x'
	}
	
	// estimation- overall risk-sharing (ancova)
	gl sample "platnet_merge!=2"
	
	foreach Y in $outcomes { 
	regdyad2 `Y'_2_i tij_shockx_any_2_i tix_shockx_any_2_i tjx_shockx_any_2_i ///
	tij_xshockx_any_2_i tix_xshockx_any_2_i tjx_xshockx_any_2_i shockx_any_2_i i.pclusterid age_ij_a age_ij_b `Y'_0_i if ${sample}, dyads(rid_all netid_all)
	qui sum `Y'_2_i if treat_i==0 & treat_j==0 & shockx_any_2_i==1 & ${sample}
	estadd scalar Ymean = r(mean)
	test tij_shockx_any_2_i=tij_xshockx_any_2_i
	estadd scalar chisq1 = r(p)
	test tix_shockx_any_2_i=tix_xshockx_any_2_i
	estadd scalar chisq2 = r(p)
	test tjx_shockx_any_2_i=tjx_xshockx_any_2_i
	estadd scalar chisq3 = r(p)
	eststo `Y'
	}
	
	// output latex tables
	
	#delimit ;
	
	esttab $outcomes using "${OUTPUT}/${H}", replace csv 							
	b(2) se(2) star(* 0.10 ** 0.05 *** 0.01)  		 					    	    
	stats(N Ymean chisq1 chisq2 chisq3, labels()) drop(*pclusterid age* *_0_i _cons)      
	wrap varwidth(100) varlabel()
	modelwidth(10) mlabels ("Food security score (HFIAS)" "Amount has to cover non-food expenses (<0)" "Subjective status on 10-point scale")    
	nonotes addnotes("Notes: Unit of observation is a directional dyad \textit{ij}> where dependent variable is a welfare measure for individual \textit{i}.  
	Sample includes all possible dyads within each geographic cluster. 
	Estimation procedure used is OLS with dyadic-robust standard errors.
	Standard errors are shown in parentheses. Level of significance: *** p<0.01> ** p<0.05> * p<0.10.
	Values are reported in Kenyan Shillings (Ksh)> 85 Ksh = 1 USD at the time of the study.
	Included as regressors but not shown: baseline outcome variable> absolute age difference between \textit{i} and \textit{j}> sum of age of \textit{i} and \textit{j}> geographic cluster fixed effects> and a constant.");
	
    #delimit cr

	
// END OF DO FILE 	
********************************************************************************	


